from django.shortcuts import render
from django.http import HttpResponse,JsonResponse


from myadmin.models import Users,Types,Goods,Cart,Cart,Address,Order,OrderInfo

# Create your views here.
'''

	[
		{
			'name':'手机',
			id:1,
			'sub':[
					{
						'name':'魅族',
						'goodslist':[{},{},{}]
					},
					{
						'name':'魅蓝',
						'goodslist':[{},{},{}]
					}
				]
		},
		{
			'name':'手环'
			,id:2,
			'sub':[
					{
						'name':'手环1'
						,'goodslist':[{},{},{}
					]},
					{
						'name':'手环2'
						,'goodslist':[{},{},{}
					]}
				]
		},
	]


'''
# 首页
def index(request):

	# 获取所有的二级菜单
	obs = Types.objects.exclude(pid = 0)[16:22]




	# 获取一级分类
	types = Types.objects.filter(pid=0)[0:8]
	for x in types:
		x.sub = Types.objects.filter(pid=x.id)

	

	# 分配数据
	context = {'tlist':obs,'types':types,'nm':''}



			

	return render(request,'home/index.html',context)

# 列表
def list(request,tid):

	# 接收分类id,获取分类对象
	ob = Types.objects.get(id=tid)
	data = {}
	# 判断当前分类是一级还是二级
	if ob.pid == 0:
		# 顶级分类 手机
		data['parent'] = ob
		# 获取当前类下子类
		data['typelist'] = Types.objects.filter(pid=ob.id)
		# 获取当前所有分类下的商品
		data['goodslist'] = Goods.objects.filter(tid__in=data['typelist'])

	else:
		# 二级分类 魅族,魅蓝
		data['parent'] = Types.objects.get(id=ob.pid)
		# 获取当前父类下子类
		typelist = Types.objects.filter(pid=data['parent'].id)
		# 循环当前所有子类,确定是否为当前类,追加属性
		for x in typelist:
			if x.id == ob.id:
				x.selected = True
		data['typelist'] = typelist
		# 获取当前分类下的商品
		data['goodslist'] = Goods.objects.filter(tid=ob.id)


	'''
		顶级分类  手机

		系列分类  魅族  魅蓝

		商品列表  魅族手机系列

		data = {
			顶级:手机,
			系列:[{'name':'魅族'},{'name':'魅蓝'}]
			商品:[{},{}]
		}

	'''



	# 获取所有的二级菜单
	obs = Types.objects.exclude(pid = 0)[16:22]
	a = cartnum(request)
	# 分配数据
	context = {'tlist':obs,'data':data,'nm':a}

	return render(request,'home/list.html',context)

# 详情
def info(request,gid):
	try:
		# 根据商品id,获取商品信息
		ob = Goods.objects.get(id=gid)
		# 增加点击量
		ob.clicknum += 1
		ob.save()
		# 获取所有的二级菜单
		obs = Types.objects.exclude(pid = 0)[16:22]
		a = cartnum(request)
		# 分配数据
		context = {'tlist':obs,'ginfo':ob,'nm':a}
		return render(request,'home/info.html',context)
	except:
		# pass
		# 报404
		raise Http404("纳尼,怎么不见了?")



# 购物车添加
def cartadd(request):
	try:
		# 用户id,商品id,购买数量num
		data = {}
		data['uid'] = Users.objects.get(id=request.session['VipUser']['uid'])
		data['gid'] = Goods.objects.get(id=request.GET.get('gid'))
		data['num'] = request.GET.get('num')

		# 根据用户id,判断当前用户的购物车中是否加入了当前的商品
		res = Cart.objects.filter(uid=data['uid']).filter(gid=data['gid'])
		if res :
			# 如果有这个商品,则修改数量
			res[0].num += int(data['num'])
			res[0].save()
		else:
			# 没有这个商品.,添加到购物车
			ob = Cart.objects.create(**data)

		return JsonResponse({'code':0,'msg':'添加购物车成功'})
	except:
		return JsonResponse({'code':1,'msg':'添加购物车失败'})

#购物车列表
def cartindex(request):
	a = cartnum(request)
	if a != 0:
		# 需要根据用户id获取当前用户购物车的信息
		data = Cart.objects.filter(uid=request.session['VipUser']['uid'])
		

		# 分配数据
		context = {'cartlist':data,'tlist':Types.objects.exclude(pid = 0)[16:22]}
		# 加载模板
		return render(request,'home/cart.html',context)
	elif a == 0:
		return render(request,'home/cart404.html')
def cartdelete(request):


	try:
		gid = request.GET['gid']
		# print(gid)
		uid = request.session['VipUser']['uid']
		# print(uid)
		#删除当前用户下的该商品

		# 获取id,执行删除
		ob = Cart.objects.filter(uid=uid).filter(gid=gid)[0]
		ob.delete()
		return JsonResponse({'code':0,'msg':'删除成功'})
	except:
		return JsonResponse({'code':1,'msg':'删除失败'})

#清空购物车
def cartclear(request):
	#获取uid
	try:
		uid = request.session['VipUser']['uid']
		#清空购物车
		obs = Cart.objects.filter(uid=uid)

		obs.delete()

		return HttpResponse('<script>alert("删除成功");location.href="/cart/index/";</script>')
	except:
		return HttpResponse('<script>alert("删除失败");location.href="/cart/index/";</script>')


# 购物车商品的数量更新
def cartedit(request):
	try:
		# 商品id,商品最新数量
		gid = request.GET['gid']
		num = request.GET['num']

		print(gid,num)
		# print(type(gid),type(num))

		# 获取购物车数据对象
		obs = Cart.objects.filter(uid=request.session['VipUser']['uid']).filter(gid=gid)[0]
		obs.num = int(num)
		obs.save()

	 
		return JsonResponse({'code':0,'msg':'购物车数量更新成功'})
	except:
		return JsonResponse({'code':1,'msg':'购物车数量更新失败'})

# 
def cartnum(request):

	nextpath = request.GET.get('next','/')

	if request.session['VipUser'] != '': 
		uid=request.session['VipUser']['uid']
		obs = Cart.objects.filter(uid=uid)

		# 计算总价
		nm = 0
		for x in obs:
			nm += x.num
		return  nm
	else:
		return ''	



# 确认订单
def confirmorder(request):
	# 获取已经选择的购物车的商品  cart id
	ids = eval(request.GET['ids'])
	# 根据选择的购物车商品,获取对象,显示到页面中
	obs = Cart.objects.filter(id__in=ids)

	# 计算总价
	num = 0
	totalprice = 0
	for x in eval(request.GET['ids']):
		cart = Cart.objects.get(id=x)
		totalprice += cart.num * cart.gid.price
		num += cart.num

	# 分配数据
	context = {'cartlist':obs,'totalprice':totalprice,'num':num}
	
	# 加载模板
	return render(request,'home/confirmorder.html',context)


# 添加新地址
def addressinsert(request):
	# 接受参数
	data = request.POST.dict()
	ids = data['ids']
	del data['csrfmiddlewaretoken']
	del data['ids']

	# 获取用户对象
	data['uid'] = Users.objects.get(id=request.session['VipUser']['uid'])
	# 执行地址添加
	ob = Address.objects.create(**data)


	return HttpResponse('<script>location.href="/confirm/order/?ids='+ids+'"</script>')

# 设置默认地址
def addressset(request):
	# 接受id,获取用户id,在修改
	aid = request.GET['aid']
	uid = request.session['VipUser']['uid']

	# 先获取当前用户的所有地址
	obs = Address.objects.filter(uid=uid)
	obs.update(isSelect=0)
	ob = obs.get(id=aid)
	ob.isSelect = True
	ob.save()

	return HttpResponse('addressset')


# 订单的提交  创建订单
def orderinsert(request):

	# 获取数据
	data = request.POST.dict()
	# 计算总价
	totalprice = 0
	for x in eval(data['ids']):
		cart = Cart.objects.get(id=x)
		totalprice += cart.num * cart.gid.price


	# 准备创建订单
	ob = Order()
	# 获取用户对象
	ob.uid = Users.objects.get(id=request.session['VipUser']['uid'])
	# 获取地址对象
	ob.addressid = Address.objects.get(id=data['addressid'])
	# 设置总价
	ob.totalprice = totalprice
	# 设置状态
	ob.status = 1
	# 执行添加
	ob.save()

	# 创建订单详情
	for x in eval(data['ids']):
		# 购物车对象
		cart = Cart.objects.get(id=x)
		# 执行订单详情的创建
		order = OrderInfo()
		order.orderid = ob
		order.goodsid = cart.gid
		order.num = cart.num
		order.price = cart.gid.price
		order.save()
		# 在购物车中删除已下单的购物车商品
		cart.delete()


	# 注意:在创建订单的视图函数中,不能直接返回模板,而是要重定向到其它位置
	# 要避免当前请求重复提交 因为这个请求是post发送,并且视图函数中在创建订单,

	# 跳转到 付款  页面
	return HttpResponse('<script>alert("订单创建成功,请付款");location.href="/buyjia/'+str(ob.id)+'/"</script>')


# 付款页面
def buyjia(request,oid):
	# 根据订单id,获取订单信息,显示支付页面
	order = Order.objects.get(id=oid)

	context = {'order':order}

	return render(request,'home/buy.html',context)



# 我的订单
def myorders(request):
	# 根据 session的用户id.获取当前用户的所有订单
	orders = Order.objects.filter(uid=request.session['VipUser']['uid'])

	context = {'orders':orders}

	return render(request,'home/myorder.html',context)

# 我的地址
def odedit(request):
	# 根据 session的用户id.获取当前用户的所有地址
	adds = Address.objects.filter(uid=request.session['VipUser']['uid'])

	context = {'adds':adds}
	return render(request,'home/odedit.html',context)

# 注册
def register(request):
	if request.method == 'GET':
		return render(request,'home/register.html')

	elif request.method == 'POST':
		# 获取数据
		data = request.POST.dict()
		del data['csrfmiddlewaretoken']


		# 验证手机号和验证码是否正确
		if data['phone'] == request.session['sendsms']['phone'] and data['code'] == request.session['sendsms']['code']:

			# 进行密码加密
			from django.contrib.auth.hashers import make_password, check_password
			data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')


			try:
				del data['code']
				# 执行注册
				ob = Users.objects.create(**data)
				return HttpResponse('<script>alert("注册成功,请登录");location.href="/login/"</script>')

			except:
				return HttpResponse('<script>alert("注册失败");location.href="/register/"</script>')
		else:
			return HttpResponse('<script>alert("验证码错误");location.href="/register/"</script>')
			
# 登录
def login(request):
	# 可以获取上一次的请求路径
	nextpath = request.GET.get('next','/')

	if request.method == 'GET':
		return render(request,'home/login.html')

	elif request.method == 'POST':
		# 获取数据
		data = request.POST.dict()
		del data['csrfmiddlewaretoken']


		# 先判断手机号用户是否存在
		try:
			ob = Users.objects.get(phone=data['phone'])

			# 再检测密码是否正确

			# 判断密码
			from django.contrib.auth.hashers import check_password
			# 检测密码
			if check_password(data['password'],ob.password):

				# 执行登录
				request.session['VipUser'] = {'uid':ob.id,'uname':ob.username,'phone':ob.phone,'pic':ob.pic}
				return HttpResponse('<script>alert("欢迎登陆");location.href="'+nextpath+'"</script>')
				
		except:
			pass


		return HttpResponse('<script>alert("用户名或密码错误");history.back(-1);</script>')


# 退出登录
def homelogouts(request):
	

	# 可以获取上一次的请求路径
	nextpath = request.GET.get('next','/')

	if request.session['VipUser'] == '':
		return HttpResponse('<script>alert("你尚未登陆");location.href="'+nextpath+'"</script>')
	else:
		request.session['VipUser'] = ''
		return HttpResponse('<script>alert("退出成功,欢迎下次登陆");location.href="'+nextpath+'"</script>')


# 短信测试
def sendsms(request):
	from dysms import demo_sms_send
	import random

	# 获取手机号
	phone = request.GET['phone']
	# 随机验证码
	code = random.randrange(1000,9999)
	print(code)
	print(phone)

	# 把随机的验证码存入session
	request.session['sendsms']  = {'phone':phone,'code':str(code)}

	# 执行验证码的发送
	res = demo_sms_send.send(str(code),phone)
	res = eval(res)
	# print(res)
	# {'Message': '触发分钟级流控Permits:1', 'RequestId': '028116A1-82CA-4F78-A6E5-A93D53EA1B6B', 'Code': 'isv.BUSINESS_LIMIT_CONTROL'}

	if res['Code'] == 'OK':
		# 发送成功
		return JsonResponse({'code':0,'msg':'发送成功'})
	else:
		# 发送失败
		return JsonResponse({'code':1,'msg':'发送失败','error':res['Message']})

